package com.beidasoft.web.util.systemSecurity;


import com.beidasoft.web.exception.system.LogException;
import com.beidasoft.web.util.Log4jUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Created by hoax on 2019-09-16 10:45.
 */
public class XssFilterWrapper extends HttpServletRequestWrapper {
    public XssFilterWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 对数组参数进行特殊字符过滤
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] returnValues = null;
        try {
            if ("v".equals(name)) {//不想过滤的参数，此处content参数是 富文本内容
                return super.getParameterValues(name);
            }
            String[] values = super.getParameterValues(name);

            if (null != values && !"".equals(values)) {
                String[] newValues = new String[values.length];
                for (int i = 0; i < values.length; i++) {
                    //newValues[i] = values[i];
                    newValues[i] = cleanXSS(values[i]);
                    //newValues[i] = HtmlUtils.htmlEscape(values[i]);//spring的HtmlUtils进行转义
                }

                //如果该参数是文件路径或文件真实名称，进一步过滤路径特殊字符
                String lowCaseName = name.toLowerCase();
                if (lowCaseName.contains("realname") || lowCaseName.contains("path")) {
                    for (int i = 0; i < values.length; i++) {
                        newValues[i] = values[i].replace("../", "");
                        newValues[i] = newValues[i].replace("./", "");
                    }
                }
                //过滤程序执行完毕，设置返回内容
                returnValues = newValues;
            } else {
                returnValues = values;
            }
        } catch (Exception e) {
            Log4jUtil.SYSTEM_LOG.error(new LogException("角色权限查询操作发生错误", e));
        }
        return returnValues;
    }

    /**
     * 清理XSS
     *
     * @param value
     * @return
     */
    private String cleanXSS(String value) {
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        return value;
    }
}
